package com.demo.index;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.demo.blog.Blog;
import com.jfinal.core.Controller;
import com.rm.system.Constants;
import com.rm.system.UrlConfig;
import com.rm.system.model.User;

/**
 * IndexController
 */
public class IndexController extends Controller {
	public void index() {
		render("index.html");
	}

	public void jump() {
		render("jump.html");
	}

	public void loginView() {
		render("login.html");
	}

	public void login() {
		String username = getPara("username");
		String password = getPara("password");
		// String[] result = RSA.decryptUsernameAndPwd(getPara("key"));
		// Sec.md5(result[1]) 密码
		try {
			UsernamePasswordToken token = new UsernamePasswordToken(username,
					password);
			Subject subject = SecurityUtils.getSubject();
			if (!subject.isAuthenticated()) {
				token.setRememberMe(true);
				subject.login(token);
				subject.getSession(true).setAttribute(Constants.SESSION_USER,
						User.dao.findByName(username));
			}

			// Log.dao.insert(this, Log.EVENT_LOGIN);

			redirect("/");

		} catch (UnknownAccountException e) {

			forwardAction("用户名不存在", UrlConfig.LOGIN);

		} catch (IncorrectCredentialsException e) {
			forwardAction("密码错误", UrlConfig.LOGIN);

		} catch (LockedAccountException e) {
			forwardAction("对不起 帐号被封了", UrlConfig.LOGIN);
			e.printStackTrace();
		} catch (ExcessiveAttemptsException e) {
			forwardAction("尝试次数过多 请明天再试", UrlConfig.LOGIN);
		} catch (AuthenticationException e) {
			forwardAction("对不起 没有权限 访问", UrlConfig.LOGIN);

		} catch (Exception e) {
			e.printStackTrace();
			forwardAction("请重新登录", UrlConfig.LOGIN);
		}
	}

	public void forwardAction(String msg, String url) {
		System.out.println(msg);
		setAttr("msg", msg);
		forwardAction(url);
	}

	public void unauthorized() {
		render(UrlConfig.VIEW_ERROR_401);
	}

	/**
	 * 测试在 maven 下的 jstl 输出功能 1：确保 web.xml 内容的 app-app 标记中的servlet版本号至少为
	 * 2.5，内容如下： <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 * xmlns="http://java.sun.com/xml/ns/javaee"
	 * xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	 * xsi:schemaLocation=
	 * "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	 * id="WebApp_ID" version="2.5"> 2：确保 jsp 页面中引用了 jstl 标记库，内容如下： <%@ taglib
	 * uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3：确保 jetty
	 * 下开发时引入了正确的依赖，详情在 pom.xml 中有注释说明
	 */
	public void jstl_test() {
		setAttr("blogList", Blog.me.find("select * from blog"));
		renderJsp("/jstl_test.jsp");
	}
}
